//
//  ReverseLinkedList.swift
//  LeetCodeSwift
//
//  Created by XFB on 2019/8/5.
//  Copyright © 2019 XFB. All rights reserved.
//  206 反转链表

import Foundation
import UIKit

class ReverseLinkedList {
    
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public var val: Int              数据域
     *     public var next: ListNode?       指针域
     *     public init(_ val: Int) {        构造函数
     *         self.val = val
     *         self.next = nil
     *     }
     * }
     */
    
    /// 单向链表的节点
    public class ListNode {
        public var val: Int
        public var next: ListNode?
        public init(_ val: Int) {
            self.val = val
            self.next = nil
        }
    }
    
    /**
     1 -> 2 -> 3 -> NULL
     
     new_head
     head
     next
     */
    
    
    /// 定义一个链表
    func reverseList(_ head: ListNode?) -> ListNode? {
        
        /// 链表头节点指针
        var new_head : ListNode?
        var firstHead = head

        while (firstHead != nil) {
            /// 1、备份next
            let next = firstHead?.next
            /// 2、更新firstHead.next
            firstHead?.next = new_head
            /// 3、移动nex_head
            new_head = firstHead
            /// 4、遍历链表
            firstHead = next
        }
        return new_head
    }
}
